package cn.bone.ou.community.service.impl;

import cn.bone.base.annotation.MyLogger;
import cn.bone.base.auth.JWTFactory;
import cn.bone.base.bean.CommonResult;
import cn.bone.base.bean.DataGrid;
import cn.bone.base.bean.Ref;
import cn.bone.base.dict.Dict;
import cn.bone.base.utils.Md5Util;
import cn.bone.base.utils.TimeUtil;
import cn.bone.ou.cache.RegionCache;
import cn.bone.ou.community.bean.Community;
import cn.bone.ou.community.bean.CommunityMng;
import cn.bone.ou.community.mapper.CommunityMapper;
import cn.bone.ou.community.mapper.CommunityMngMapper;
import cn.bone.ou.community.param.MngParam;
import cn.bone.ou.community.service.ICommunityMngService;
import cn.bone.ou.community.vo.CommunityMngVo;
import cn.bone.ou.community.vo.MngVo;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Service
@Transactional
public class CommunityMngServiceImpl implements ICommunityMngService {

    @Resource
    private CommunityMngMapper communityMngMapper;
    @Resource
    private CommunityMapper communityMapper;
    @Resource
    private JWTFactory jwtFactory;
    @Resource
    private RegionCache regionCache;

    /**管理员登录*/
    @MyLogger(msg = "管理员登录")
    public CommonResult<MngVo.LoginVo> login(MngParam.LoginParam param){

        CommunityMng mng = communityMngMapper.getByPhoneNum(param.getPhoneNum());
        if(mng==null){
            return Ref.error("错误的手机号或密码");
        }
        String dbPass = Md5Util.makePwd(param.getPassword(), mng.getSalt());
        if(!dbPass.equals(mng.getPassword())){
            return Ref.error("错误的手机号或密码");
        }
        if(mng.getUsable()==0){
            return Ref.error("该账号不可用");
        }
        if(mng.getIsDelete()==1){
            return Ref.error("该账号不可用");
        }
        Community community = communityMapper.selectById(mng.getCommunityId());
        if(community==null){
            return Ref.error("数据异常");
        }
        if(community.getUsable()==0){
            return Ref.error("所属小区不可用,请联系管理员");
        }

        //创建token
        String token = jwtFactory.createToken(mng.getId(), Dict.MemberType.manager, "web");
        MngVo.LoginVo vo = new MngVo.LoginVo();
        vo.setMngId(mng.getId());
        vo.setPhoneNum(mng.getPhoneNum());
        vo.setRealName(mng.getRealName());
        vo.setHeadImg(mng.getHeadImg());
        vo.setToken(token);

        vo.setCommunityId(community.getId());
        vo.setCommunityName(community.getName());
        vo.setProvinceName(regionCache.get(community.getProvince()).getName());
        vo.setCityName(regionCache.get(community.getCity()).getName());
        vo.setDistrictName(regionCache.get(community.getDistrict()).getName());
        vo.setAddress(community.getAddress());

        return Ref.ok(vo);
    }

    /**获取管理员信息*/
    public CommonResult<MngVo.InfoVo> info(MngParam.InfoParam param){
        CommunityMng mng = communityMngMapper.selectById(param.getMngId());
        if(mng==null){
            return Ref.error("错误的用户id");
        }
        Community community = communityMapper.selectById(mng.getCommunityId());
        if(community==null){
            return Ref.error("数据异常");
        }
        MngVo.InfoVo vo = new MngVo.InfoVo();
        vo.setMngId(mng.getId());
        vo.setPhoneNum(mng.getPhoneNum());
        vo.setRealName(mng.getRealName());
        vo.setHeadImg(mng.getHeadImg());

        vo.setCommunityId(community.getId());
        vo.setCommunityName(community.getName());
        vo.setProvinceName(regionCache.get(community.getProvince()).getName());
        vo.setCityName(regionCache.get(community.getCity()).getName());
        vo.setDistrictName(regionCache.get(community.getDistrict()).getName());
        vo.setAddress(community.getAddress());

        return Ref.ok(vo);
    }

    /**修改头像*/
    @MyLogger(msg = "管理员修改头像")
    public CommonResult modifyHeadImg(MngParam.ModifyHeadImgParam param){
        CommunityMng mng = communityMngMapper.selectById(param.getMngId());
        if(mng==null){
            return Ref.error("错误的用户id");
        }
        mng.setHeadImg(param.getHeadImg());
        communityMngMapper.updateById(mng);
        return Ref.ok();
    }

    /**修改姓名*/
    @MyLogger(msg = "管理员修改姓名")
    public CommonResult modifyRealName(MngParam.ModifyRealNameParam param){
        CommunityMng mng = communityMngMapper.selectById(param.getMngId());
        if(mng==null){
            return Ref.error("错误的用户id");
        }
        mng.setRealName(param.getRealName());
        communityMngMapper.updateById(mng);
        return Ref.ok();
    }


    /**修改手机号*/
    @MyLogger(msg = "管理员修改手机号")
    public CommonResult modifyPhoneNum(MngParam.ModifyPhoneNumParam param){
        CommunityMng mng = communityMngMapper.selectById(param.getMngId());
        if(mng==null){
            return Ref.error("错误的用户id");
        }
        mng.setPhoneNum(param.getPhoneNum());
        communityMngMapper.updateById(mng);
        return Ref.ok();
    }

    /**修改密码*/
    @MyLogger(msg = "管理员修改密码")
    public CommonResult modifyPass(MngParam.ModifyPassParam param){
        CommunityMng mng = communityMngMapper.selectById(param.getMngId());
        if(mng==null){
            return Ref.error("错误的用户id");
        }
        String salt = mng.getSalt();
        String dbPass = Md5Util.makePwd(param.getPassword(), salt);
        if(!dbPass.equals(mng.getPassword())){
            return Ref.error("密码错误");
        }
        String newPass = Md5Util.makePwd(param.getNewPass(), salt);
        mng.setPassword(newPass);
        communityMngMapper.updateById(mng);
        return Ref.ok();
    }

    /**管理员列表*/
    public CommonResult<DataGrid<CommunityMngVo.ListVo>> list(MngParam.ListParam param){
        List<CommunityMng> mngs = communityMngMapper.listNotDel(
                param.getCommunityId(), param.getStart(), param.getNum());
        int count = communityMngMapper.countListNotDel(param.getCommunityId());
        List<CommunityMngVo.ListVo> vos = mngs.stream().map(mng->{
            CommunityMngVo.ListVo vo = new CommunityMngVo.ListVo();
            vo.setMngId(mng.getId());
            vo.setRealName(mng.getRealName());
            vo.setPhoneNum(mng.getPhoneNum());
            vo.setLastLoginTime(mng.getUpdateTime()==null?"": TimeUtil.formaterYYYYMMddHHmm(mng.getUpdateTime()));
            vo.setUsable(mng.getUsable());
            return vo;
        }).collect(Collectors.toList());

        DataGrid<CommunityMngVo.ListVo> dataGrid = new DataGrid<>();
        dataGrid.setTotal(count);
        dataGrid.setRows(vos);
        return Ref.ok(dataGrid);
    }

    /**添加管理员*/
    @MyLogger(msg = "添加管理员")
    public CommonResult add(MngParam.AddParam param){
        CommunityMng communityMng = communityMngMapper.getByPhoneNum(param.getPhoneNum());
        if(communityMng!=null){
            return Ref.error("该手机号已存在");
        }
        String salt = Md5Util.getSalt();
        String dbPass = Md5Util.makePwd(param.getPassword(), salt);
        Date date = new Date();

        communityMng = new CommunityMng();
        communityMng.setCommunityId(param.getCommunityId());
        communityMng.setPhoneNum(param.getPhoneNum());
        communityMng.setSalt(salt);
        communityMng.setPassword(dbPass);
        communityMng.setRealName(param.getRealName());
        communityMng.setUsable(1);
        communityMng.setIsDelete(0);
        communityMng.setCreateMemberId(1);
        communityMng.setCreateTime(date);
        communityMng.setUpdateMemberId(1);
        communityMng.setUpdateTime(date);
        communityMngMapper.insert(communityMng);
        return Ref.ok();
    }

    /**修改管理员*/
    @MyLogger(msg = "修改管理员")
    public CommonResult modify(MngParam.ModifyParam param){
        CommunityMng mng = communityMngMapper.getByPhoneNumAndId(param.getPhoneNum(),
                param.getMngId());
        if(mng!=null){
            return Ref.error("该手机号已存在");
        }
        mng = communityMngMapper.selectById(param.getMngId());
        if(mng==null){
            return Ref.error("错误的管理员编号");
        }
        mng.setPhoneNum(param.getPhoneNum());
        mng.setRealName(param.getRealName());
        communityMngMapper.updateById(mng);
        return Ref.ok();
    }

    /**删除管理员*/
    @MyLogger(msg = "删除管理员")
    public CommonResult delete(MngParam.DeleteParam param){
        CommunityMng communityMng = communityMngMapper.selectById(param.getMngId());
        if(communityMng==null){
            return Ref.error("错误的管理员编号");
        }
        communityMng.setIsDelete(1);
        communityMngMapper.updateById(communityMng);
        return Ref.ok();
    }

    /**启用管理员*/
    @MyLogger(msg = "启用管理员")
    public CommonResult usable(MngParam.UsableParam param){
        CommunityMng communityMng = communityMngMapper.selectById(param.getMngId());
        if(communityMng==null){
            return Ref.error("错误的管理员编号");
        }
        communityMng.setUsable(1);
        communityMngMapper.updateById(communityMng);
        return Ref.ok();
    }


    /**禁用管理员*/
    @MyLogger(msg = "禁用管理员")
    public CommonResult disable(MngParam.DisableParam param){
        CommunityMng communityMng = communityMngMapper.selectById(param.getMngId());
        if(communityMng==null){
            return Ref.error("错误的管理员编号");
        }
        communityMng.setUsable(0);
        communityMngMapper.updateById(communityMng);
        return Ref.ok();
    }

    /**重置密码*/
    @MyLogger(msg = "重置管理员密码")
    public CommonResult resetPass(MngParam.ResetPassParam param){
        CommunityMng communityMng = communityMngMapper.selectById(param.getMngId());
        if(communityMng==null){
            return Ref.error("错误的管理员编号");
        }
        String salt = Md5Util.getSalt();
        String dbPass = Md5Util.makePwd(param.getNewPass(), salt);
        communityMng.setSalt(salt);
        communityMng.setPassword(dbPass);
        communityMngMapper.updateById(communityMng);
        return Ref.ok();
    }
}
